package com.winhxd.b2c.customer.api;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.AdminUserStoreIdConstant;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.context.UserContext;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.CustomerPageConfigCondition;
import com.winhxd.b2c.common.domain.customer.condition.QueryPageConfigCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerPageConfig;
import com.winhxd.b2c.common.domain.customer.model.CustomerUserInfo;
import com.winhxd.b2c.common.domain.customer.vo.CustomerPageConfigVO;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.mq.MQDestination;
import com.winhxd.b2c.common.mq.StringMessageSender;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.service.CustomerStoreInfoSerivce;
import com.winhxd.b2c.customer.service.PageConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: hxd-outlet-parent
 * @description: 小程序登录获取首页
 * @author: ChenYanqi
 * @create: 2019-01-11 20:05
 **/
@Api(tags = "Api - CustomerPageConfig")
@RestController
@RequestMapping(value = "/api-customer/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ApiPageConfigController {


    private static final Logger logger = LoggerFactory.getLogger(ApiPageConfigController.class);

    @Autowired
    private PageConfigService pageConfigService;
    @Autowired
    private CustomerStoreInfoSerivce customerStoreInfoSerivce;
    @Autowired
    private Cache cache;

    @Autowired
    StringMessageSender stringMessageSender;


    @ApiOperation(value = "小程序登录获取首页配置", notes = "小程序登录获取首页配置")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
    })
    @RequestMapping(value = "customer/2408/v1/getHomePage", method = RequestMethod.POST)
    public ResponseResult<String> getHomePage(@RequestBody CustomerPageConfigCondition configCondition) {
        logger.info("customer/2408/v1/getHomePage 接口的入参为: - {}", JsonUtil.toJSONString(configCondition));
        Long customerId = UserContext.getCurrentCustomerUser().getCustomerId();
        // 统计当日用户数量
        stringMessageSender.send(MQDestination.TODAY_USER_NUMBER_MESSAGE,String.valueOf(customerId));
        Long storeId;
        //通过customerId 获取 storeId
        CustomerUserInfo customerUser = customerStoreInfoSerivce.getCustomerUserById(customerId);
        if (CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode().intValue() == customerUser.getLevel() ||
                CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode().intValue() == customerUser.getLevel()) {
            storeId = customerUser.getId();
        } else {
            //上级id
            Long parentId = customerUser.getParentId();
            if (parentId == null) {
                storeId = AdminUserStoreIdConstant.ADMIN_USER_STORE_ID;
            } else {
                storeId = parentId;
            }
        }
        String pageDetails;
        pageDetails = cache.hget(CacheName.HOME_PAGE_CONFIGURATION, storeId + "");
        if (pageDetails == null) {
            CustomerPageConfig customerPageConfig = pageConfigService.selectHomePageByStoreId(storeId);
            if (customerPageConfig == null) {
                //获取原译默认的主页
                pageDetails = cache.hget(CacheName.HOME_PAGE_CONFIGURATION, AdminUserStoreIdConstant.ADMIN_USER_STORE_ID + "");
                if (pageDetails == null) {
                    CustomerPageConfig pageConfig = pageConfigService.selectHomePageByStoreId(AdminUserStoreIdConstant.ADMIN_USER_STORE_ID);
                    CustomerPageConfigVO customerPageConfigVO = new CustomerPageConfigVO();
                    customerPageConfigVO.setPageTitle(pageConfig.getPageTitle());
                    customerPageConfigVO.setPageDetail(pageConfig.getPageDetail());
                    pageDetails = JsonUtil.toJSONString(customerPageConfigVO);
                    cache.hset(CacheName.HOME_PAGE_CONFIGURATION, AdminUserStoreIdConstant.ADMIN_USER_STORE_ID + "", pageDetails);
                    cache.expire(CacheName.HOME_PAGE_CONFIGURATION, Integer.valueOf(DurationFormatUtils.formatDuration(24 * 60 * 60 * 1000, "s")));
                }
            } else {
                CustomerPageConfigVO customerPageConfigVO = new CustomerPageConfigVO();
                customerPageConfigVO.setPageTitle(customerPageConfig.getPageTitle());
                customerPageConfigVO.setPageDetail(customerPageConfig.getPageDetail());
                pageDetails = JsonUtil.toJSONString(customerPageConfigVO);
                cache.hset(CacheName.HOME_PAGE_CONFIGURATION, storeId + "", pageDetails);
                cache.expire(CacheName.HOME_PAGE_CONFIGURATION, Integer.valueOf(DurationFormatUtils.formatDuration(24 * 60 * 60 * 1000, "s")));
            }

        }
        ResponseResult<String> responseResult = new ResponseResult<>();
        responseResult.setData(pageDetails);
        return responseResult;
    }


    @ApiOperation(value = "小程序根据页面id获取页面配置的详情", notes = "小程序根据页面id获取页面配置的详情")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "操作成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
    })
    @RequestMapping(value = "customer/2409/v1/getPageConfigById", method = RequestMethod.POST)
    public ResponseResult<String> getPageConfigById(@RequestBody QueryPageConfigCondition condition) {
        logger.info("customer/2409/v1/getPageConfigById 接口的入参为: - {}", JsonUtil.toJSONString(condition));
        Long id = condition.getId();
        CustomerPageConfig customerPageConfig = pageConfigService.selectPageConfigById(id);
        if (ObjectUtils.isEmpty(customerPageConfig)) {
            throw new BusinessException(BusinessCode.CODE_240901);
        }
        CustomerPageConfigVO customerPageConfigVO = new CustomerPageConfigVO();
        customerPageConfigVO.setPageDetail(customerPageConfig.getPageDetail());
        customerPageConfigVO.setPageTitle(customerPageConfig.getPageTitle());
        ResponseResult<String> responseResult = new ResponseResult<>();
        responseResult.setData(JsonUtil.toJSONString(customerPageConfigVO));
        return responseResult;
    }

}
